package dp05.leertaak1.server.protocol;

import java.util.Stack;

import dp05.leertaak1.command.definitions.Command;
import dp05.leertaak1.command.definitions.RevertableCommand;
import dp05.leertaak1.command.implementations.Get;
import dp05.leertaak1.command.implementations.Insert;
import dp05.leertaak1.command.implementations.Total;
import dp05.leertaak1.command.implementations.Update;
import dp05.leertaak1.server.ClientHandler.Action;
import dp05.leertaak1.server.Server;

public class ProtocolDbAvailable extends Protocol
{
    private Stack<RevertableCommand> actionStack = new Stack<RevertableCommand>();
    private Stack<RevertableCommand> undoStack = new Stack<RevertableCommand>();

    @Override
    public String createAndExecuteCommand(Action currentAction, String[] parameters)
    {
        String returnMessage = null;
        Command currentCommand = null;

        switch (currentAction)
        {
            case GET:
                currentCommand = new Get(Server.dao);
                returnMessage = currentCommand.execute();
                break;
            case INSERT:
                if (parameters.length > 1)
                {
                    int value = 0;
                    try
                    {
                        value = Integer.parseInt(parameters[1]);
                    } catch (NumberFormatException nfe)
                    {
                        return "Please enter a real number";
                    }
                    currentCommand = new Insert(Server.dao, value);
                    returnMessage = currentCommand.execute();
                    actionStack.add((RevertableCommand) currentCommand);
                }
                break;
            case TOTAL:
                currentCommand = new Total(Server.dao);
                returnMessage = currentCommand.execute();
                break;
            case CLOSE:
                currentCommand = new Update(Server.dao);
                returnMessage = currentCommand.execute();
                break;
            case UNDO:
                RevertableCommand undo = actionStack.pop();
                returnMessage = undo.undo();
                undoStack.push(undo);
                break;
            case REDO:
                RevertableCommand redo = undoStack.pop();
                returnMessage = "Command '" + redo.toString() + "' is redone";
                actionStack.push(redo);
                break;
            default:
                returnMessage = "Invalid command";
                break;

        }
        return returnMessage;
    }

}
